<?php
declare(strict_types=1);
namespace Helper;
class BitMap
{
    protected $map = [];

    /**
     * BitMap constructor.
     * @param string $data
     */
    public function __construct(string $data = "")
    {
        $this->map = [];
        if ($data) {
            foreach (explode(';', $data) as $row) {
                [$k, $v] = explode(',', $row);
                $this->map[$k] = $v;
            }
        }
    }

    /**
     * @param $value
     * @return int
     */
    private function getIndex($value): int
    {
        return $value >> 5;
    }

    /**
     * @param $value
     */
    public function set($value): void
    {
        $index = $this->getIndex($value);
        if (isset($this->map[$index])) {
            $this->map[$index] |= 1 << ($value & 31);
        } else {
            $this->map[$index] = 1 << ($value & 31);
        }
    }

    /**
     * @param $value
     * @return bool
     */
    public function has($value): bool
    {
        $index = $this->getIndex($value);
        return isset($this->map[$index]) ? ($this->map[$index] & (1 << ($value & 31))) == (1 << ($value & 31)) : false;
    }

    /**
     * @return string
     */
    public function out(): string
    {
        $arr = [];
        foreach ($this->map as $k => $v) {
            $arr[] = $k . ',' . $v;
        }
        return implode(';', $arr);
    }
}

